// pages/template/template.js
const http = require("../../api/http")
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    a4Width: 0,
    a4Height: 0,
    padding: 0,
    scaleFactor: 1,
    templateNo: '',
    border: '1px solid #ccc',
    templateStyle: {},
    templateParam: {},
    originalTemplateParamJSON: '', // 编辑时的原始数据
    show: false,
    imageList: [],
    imageIndex: 0,
    formData: {
      name: '',
      price: '',
      unit: '',
    },
    selectedImage: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const _this = this
    const templateParam = this.templateParam || {}
    this.setData({
      templateNo: options.templateId,
    })
    if (options.printId !== 'undefined' && options.printId !== '') {
      this.taskId = options.printId
      http.post("/print-task/queryPrintDataById", {
        id: options.printId
      }).then((res) => {
        const { templateData, templateId } = res.data
        for (const template of templateData) {
          template.src = template.original
        }
        templateParam[templateId] = templateData
        _this.setData({
          templateParam: templateParam,
          originalTemplateParamJSON: JSON.stringify(templateParam)
        })
      })
    } else {
      http.get(`/print-task/getDraft/${options.templateId}`).then((data) => {
        const templates = data.data
        for (const key in templates) {
          for (const temp of templates[key]) {
            temp.src = temp.original
          }
        }
        _this.setData({
          templateParam: templates
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init()
    const data = this.data.selectedImage
    if (data && data.hasOwnProperty('path')) {
      this.handleSelectedImg(this.data.selectedImage)
    }
  },
  /**
   * 初始化
   */
  init() {
    // 计算A4纸尺寸（转换为像素）
    const a4WidthPx = this.calculateScale(210)
    const a4HeightPx = this.calculateScale(297)
    const paddingPx = this.calculateScale(10)
    // 按宽度缩放
    const scaleFactor = (wx.getWindowInfo().screenWidth - 60) / a4WidthPx
    const templateNo = this.data.templateNo
    const templateStyle = this.data.templateStyle
    switch (templateNo) {
      case '1':
        const imageHeight = this.calculateScale(260)
        templateStyle[templateNo] = { 'imageHeight': imageHeight * scaleFactor }
        break
      case '2':
      case '3':
      case '4':
        const imageHeight2 = this.calculateScale(120)
        const imageWidth = this.calculateScale(90)
        templateStyle[templateNo] = { 'imageHeight': imageHeight2 * scaleFactor, 'imageWidth': imageWidth * scaleFactor }
        break
    }
    this.setData({
      a4Width: a4WidthPx * scaleFactor,
      a4Height: a4HeightPx * scaleFactor,
      padding: paddingPx * scaleFactor,
      scaleFactor: scaleFactor,
      templateStyle: templateStyle
    });
  },
  /**
   * 计算缩放后的大小px 1英寸等于25.4毫米 按300Dpi
   * @param {*} original 原大小
   */
  calculateScale(original) {
    const window = wx.getWindowInfo()
    const pixelRatio = window.pixelRatio
    return (original * pixelRatio * 300) / 25.4
  },
  /**
   * 模板点击事件
   * @param {Object} event 
   */
  templateClickHandle(event) {
    const { template, index } = event.currentTarget.dataset
    const templateParam = this.data.templateParam
    const _this = this
    const query = wx.createSelectorQuery();
    // 使用 event.target 获取点击的元素
    query.select(`#${event.target.id}`).boundingClientRect((rect) => {
      if (rect) {
        _this.scale = `${rect.height}:${rect.width}`
        if (templateParam[template] && templateParam[template][index] && templateParam[template][index].src) {
          wx.showActionSheet({
            itemList: ['编辑', '从图库选择'],
            success(res) {
              switch (res.tapIndex) {
                case 0:
                  // 编辑
                  _this.edit(event)
                  break
                case 1:
                  // 从图库选择
                  _this.chooseImage(event)
                  break
                default:
                  console.error("未知选项")
              }
            },
            fail: console.error
          })
        } else {
          this.chooseImage(event)
        }
      }
    }).exec();
  },
  /**
   * 编辑
   * @param {Object} event 
   */
  edit(event) {
    const { template, index } = event.currentTarget.dataset
    const templateParam = this.data.templateParam
    const temp = templateParam[template]
    const tempIndex = temp[index]
    const _this = this
    const { fileId, original } = tempIndex
    this.cropImage({
      src: original,
      cropScale: _this.scale,
      success: function (data) {
        _this.setTemplateParam(data, original, fileId)
      }
    })
  },

  /**
   * 从图库中选择图片
   * @param {*} event 
   */
  chooseImage: function (event) {
    const { index } = event.currentTarget.dataset
    const _this = this
    this.setData({
      imageIndex: index
    })
    wx.navigateTo({
      url: '/pages/album/index',
      events: {
        // 获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          _this.setData({
            selectedImage: data
          })
        },
      }
    })
  },
  /**
   * 从相册选择图片
   * @param {*} event 
   */
  _chooseImage: function (event) {
    const { template, index } = event.currentTarget.dataset
    const _this = this
    const templateParam = _this.data.templateParam
    const temp = templateParam[template] || []
    const param = temp[index] || {}
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success(res) {
        param.src = res.tempFiles[0].tempFilePath
        temp[index] = param
        templateParam[template] = temp
        _this.setData({
          templateParam: templateParam
        })
      }
    })
  },
  /**
   * 输入文字内容
   * @param {*} event 
   */
  inputText: function (event) {
    const { index } = event.currentTarget.dataset
    this.index = index
    const templateParam = this.data.templateParam
    const template = this.data.templateNo
    const temp = templateParam[template] || []
    const indexParam = temp[index] || {}
    this.setData({
      formData: {
        name: indexParam.name || '',
        price: indexParam.price || '',
        unit: indexParam.unit || ''
      },
      showFormModal: true
    })
  },
  confirm(e) {
    const formData = e.detail
    const templateParam = this.data.templateParam
    const template = this.data.templateNo
    const temp = templateParam[template] || []
    let indexParam = temp[this.index] || {}
    indexParam = { ...indexParam, ...formData }
    temp[this.index] = indexParam
    templateParam[template] = temp
    this.setData({
      templateParam
    })
  },
  save: function () {
    const { templateParam, originalTemplateParamJSON } = this.data
    const templateParamJSON = JSON.stringify(templateParam)
    if (originalTemplateParamJSON === "") {
      this.saveTemplate()
    } else {
      if (originalTemplateParamJSON === templateParamJSON) {
        this.goIndex()
      } else {
        this.saveTemplate()
      }
    }
  },
  /**
   * 保存模板
   */
  saveTemplate: function () {
    const templateNo = this.data.templateNo
    const templateJSONParam = this.data.templateParam[templateNo]
    const _this = this
    if (!templateJSONParam || templateJSONParam.length === 0) {
      wx.showToast({
        title: '请完善模板内容',
        icon: 'error'
      })
      return
    }
    for (const templateParam of templateJSONParam) {
      if (!templateParam.name) {
        wx.showToast({
          title: '请完善菜名',
          icon: 'error'
        })
        return
      }
      if (!templateParam.price) {
        wx.showToast({
          title: '请完善价格',
          icon: 'error'
        })
        return
      }
    }
    // 隐藏编辑按钮
    wx.showLoading({
      title: '保存中请求稍后',
    })
    setTimeout(() => {
      _this.uploadTemplateData(templateJSONParam, templateNo)
    })
  },
  /**
   * 上传模板数据并保存到服务器。
   * 该方法首先获取页面中指定元素的节点快照，然后上传缩略图，并将模板数据和缩略图ID一起发送到服务器进行保存。
   * @param {string} templateJsonStr - 模板数据的JSON字符串。
   * @param {string} templateNo - 模板编号
   * @returns {Promise<void>} - 返回一个Promise对象，表示上传和保存操作的完成情况。
   */
  uploadTemplateData(templateJSONParam, templateNo) {
    const _this = this
    this.createSelectorQuery()
      .select("#template")
      .node()
      .exec(res => {
        const node = res[0].node
        node.takeSnapshot({
          type: 'file',
          format: 'png',
          success: (res) => {
            //上传缩略图
            const path = res.tempFilePath
            http.uploadFile(path, { type: 2 }).then((res) => {
              http.post("/print-task/save", {
                templateId: templateNo,
                thumbnailId: res.data,
                templateData: templateJSONParam,
                id: this.taskId || null
              }).then((res) => {
                wx.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000,
                  success() {
                    _this.goIndex()
                  }
                })
              }).catch(() => {
                wx.showToast({
                  title: '保存失败',
                  icon: 'error',
                  duration: 2000
                })
              })
            })
          },
          fail(error) {
            console.error(error)
            wx.hideLoading()
          }
        })
      })
  },
  /**
   * 退出
   */
  exit: function () {
    const { templateParam, originalTemplateParamJSON } = this.data
    const templateParamJSON = JSON.stringify(templateParam)
    const _this = this
    if (originalTemplateParamJSON === "") {
      if (templateParamJSON !== "{}") {
        // 保存操作记录
        http.post('/print-task/saveDraft', { data: templateParamJSON, templateId: _this.data.templateNo }).then(() => {
          _this.goback()
        })
      } else {
        _this.goback()
      }
    } else {
      if (originalTemplateParamJSON !== templateParamJSON) {
        wx.showModal({
          title: '温馨提示',
          content: '模板已修改是否自动保存',
          complete: (res) => {
            if (res.cancel) {
              _this.goback()
            }
            if (res.confirm) {
              _this.saveTemplate()
            }
          }
        })
      } else {
        _this.goback()
      }
    }
  },
  goback() {
    wx.navigateBack({
      delta: -1,
      fail(error) {
        console.log(error)
        wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    })
  },
  goIndex() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  /**
   * 打印
   */
  print: function () {

  },
  /**
   * 保存到相册
   */
  saveToAlbum: function () {
    const _this = this
    wx.showLoading({
      title: '保存中请稍后',
    })
    this.createSelectorQuery()
      .select("#template")
      .node()
      .exec(res => {
        const node = res[0].node
        node.takeSnapshot({
          type: 'file',
          format: 'png',
          success: (res) => {
            const tempFilePath = res.tempFilePath
            wx.getSetting({
              success(res) {
                if (res.authSetting['scope.writePhotosAlbum']) {
                  _this.saveToPhotosAlbum(tempFilePath)
                } else {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      _this.saveToPhotosAlbum(tempFilePath);
                    },
                    fail(error) {
                      console.log(error)
                      wx.hideLoading()
                      wx.showModal({
                        content: '检测到您没打开相册功能权限，是否去设置打开？',
                        confirmText: "确认",
                        cancelText: "取消",
                        success: function (res) {
                          if (res.confirm) {
                            wx.openSetting({
                              success: (res) => { }
                            })
                          }
                        }
                      })
                    }
                  })
                }
              },
              fail() {
                wx.hideLoading()
              }
            })
          },
          fail(error) {
            console.error(error)
            wx.hideLoading()
          }
        })
      })
  },
  saveToPhotosAlbum(tempFilePath) {
    const fs = wx.getFileSystemManager();
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success() {
        // 删除文件
        fs.unlink({
          filePath: tempFilePath,
          success(res) {
            console.log(res)
          },
          fail(res) {
            console.error(res)
          }
        })
        wx.showToast({
          title: '保存成功',
          success() {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },
  /**
   * 处理图片选择的函数。
   * @param {Object} event - 触发事件的对象，通常包含用户选择的图片信息。
   */
  handleSelectedImg: function (data) {
    const { path, fileId } = data
    const _this = this
    this.cropImage({
      src: path,
      cropScale: _this.scale,
      success: function (data) {
        _this.setTemplateParam(data, path, fileId)
      }
    })
  },
  setTemplateParam(data, original, fileId) {
    const templateParam = this.data.templateParam || {}
    const templetNo = this.data.templateNo
    const imageIndex = this.data.imageIndex
    const temp = templateParam[templetNo] || []
    const tempIndex = temp[imageIndex] || {}
    // 剪裁路径
    tempIndex.src = data.tempFilePath
    tempIndex.cropParam = data.cropParam
    // 原路径
    tempIndex.original = original
    tempIndex.fileId = fileId
    temp[imageIndex] = tempIndex
    templateParam[templetNo] = temp
    this.setData({
      templateParam: templateParam,
      show: false
    })
  },
  cropImage(option) {
    const _this = this
    wx.navigateTo({
      url: '/pages/image-cropper/index',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          _this.setData({
            selectedImage: {}
          })
          if (!data.exit) {
            option.success(data)
          }
        },
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { imagePath: option.src, cropScale: option.cropScale })
      },
      fail: console.error
    })
  },
})